package com.mrru.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mrru.common.lang.Result;
import com.mrru.entity.Blog;
import com.mrru.service.BlogService;
import com.mrru.utils.ShiroUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
public class BlogController {

    @Autowired
    BlogService blogService;

    /**
     * 查询所有博客
     */
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage){

        Page page = new Page(currentPage, 5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));

        return Result.succ(pageData);
    }

    /**
     * 根据博客id 查询某个博客
     */
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable("id") Long id){
        Blog blog = blogService.getById(id);
        //断言做判断   条件blog在notNull时往下执行，否则抛异常 blog为空的情况返回信息给前端
        Assert.notNull(blog, "该博客已经被删除");
        return Result.succ(blog);
    }

    /**
     * 传入博客对象进行修改或者添加
     *  参数blog就是已经修改后或者新建的博客对象了
     */
    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog){
        Blog temp = null;

        if(blog.getId()!=null){//这次是修改操作
            //查到数据库的temp
            temp = blogService.getById(blog.getId());
            //只能修改自己的博客，点了别人的，要提示无权限
            //断言做判断   条件博客的用户id和当前用户id相等在isTrue时往下执行，否则抛异常
            Assert.isTrue(temp.getUserId().equals(ShiroUtil.getProfile().getId()),"没有权限编辑");
        }else {//这次是添加操作
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        BeanUtil.copyProperties(blog, temp,"id","userId","created","status");
        blogService.saveOrUpdate(temp);
        return Result.succ(temp);
    }

    @RequiresAuthentication
    @GetMapping("/blog/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        boolean isRemove = blogService.removeById(id);
        if (!isRemove){
            return Result.fail("删除失败！");
        }
        return Result.succ(null);

    }
}
